package utils

import (
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"strings"
)

// SetSecurityHeaders 设置安全HTTP头
func SetSecurityHeaders(w http.ResponseWriter) {
	w.Header().Set("X-Content-Type-Options", "nosniff")
	w.Header().Set("X-Frame-Options", "DENY")
	w.Header().Set("X-XSS-Protection", "1; mode=block")
	w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
}

// IsSafePath 检查路径是否安全，防止目录遍历攻击
func IsSafePath(p, staticFolder string) bool {
	absStaticFolder, err := filepath.Abs(staticFolder)
	if err != nil {
		return false
	}

	absPath, err := filepath.Abs(p)
	if err != nil {
		return false
	}

	return strings.HasPrefix(absPath, absStaticFolder)
}


// FormatBytes 格式化字节数为可读格式
func FormatBytes(bytes int64) string {
	const unit = 1024
	if bytes < unit {
		return fmt.Sprintf("%d B", bytes)
	}
	div, exp := int64(unit), 0
	for n := bytes / unit; n >= unit; n /= unit {
		div *= unit
		exp++
	}
	return fmt.Sprintf("%.1f %cB", float64(bytes)/float64(div), "KMGTPE"[exp])
}

// LogWithPrintf 安全的日志记录函数，处理类型断言
func LogWithPrintf(logger any, format string, args ...interface{}) {
	if logger, ok := logger.(interface{ Printf(string, ...interface{}) }); ok {
		logger.Printf(format, args...)
	}
}

// ErrorResponse 统一的错误响应函数
func ErrorResponse(w http.ResponseWriter, message string, statusCode int) {
	http.Error(w, message, statusCode)
}

// CreateSessionCookie 创建统一的Session Cookie
func CreateSessionCookie(name, value string, maxAge int) *http.Cookie {
	return &http.Cookie{
		Name:     name,
		Value:    value,
		Path:     "/",
		MaxAge:   maxAge,
		HttpOnly: true,
		Secure:   false, // 在开发环境中可以为false
		SameSite: http.SameSiteStrictMode,
	}
}

// CreateDirectory 创建目录（如果不存在）
func CreateDirectory(path string) error {
	if _, err := os.Stat(path); os.IsNotExist(err) {
		return os.MkdirAll(path, 0755)
	}
	return nil
}